import asyncio
import requests
import time
import aiohttp


def sync_test():
    for i in range(20):
        resp = requests.get('http://httpbin.org/get')
        print(f"第{i+1}个请求 ,status_code:{resp.status_code}")
        yield resp
def sync_time():
    start = time.time()
    for item in sync_test():
        print(item)
    print('耗时:',time.time() - start)



async def request_data(client,num):
    resp = await client.get(f'http://httpbin.org/get')
    print(f"第{num + 1}个请求 ,status_code:{resp.status}")
    return resp

async def async_test():
    async with aiohttp.ClientSession() as client:
        tasks = list()
        for num in range(20):
            coroutine_obj = request_data(client,num)
            task = asyncio.create_task(coroutine_obj)
            tasks.append(task)
        done,pending = await asyncio.wait(tasks)
        # print(done,pending)
        for res in done:
            print(res.result())

def async_time():
    start = time.time()
    asyncio.run(async_test())
    print('耗时:', time.time() - start)


if __name__ == '__main__':
    sync_time() # 10s
    async_time() # 不到1s